package cn.biplam.back.operator.systemManage.sysprivi.privi;

import java.util.ArrayList;

import cn.biplam.back.sql.dml.Delete;
import cn.biplam.back.sql.dml.Insert;
import cn.biplam.back.sql.dml.Update;
import cn.biplam.common.bean.md.IndexTable;
import cn.biplam.common.bean.tree.IndexTableSimple;
import cn.biplam.common.client.DataFilter;
import cn.biplam.common.client.Operator;
import cn.biplam.common.client.OperatorResult;
import cn.biplam.common.interfaces.DataOperator;
import cn.biplam.common.opcode.SysManageCode.PriviDeployOptCode;
import cn.biplam.common.paramters.TreeParam.Index_Tree_Node_Type;
import cn.biplam.common.struc.SysStruc.PriviDeployStruc;
import cn.biplam.common.struc.SysStruc.PriviStruc;
import cn.biplam.common.tools.TOOLS;
import cn.biplam.common.wrapper.ErrorMessage;

/**
 *  系统权限发布表数据操作类
 * @author XiaoRuxing Dec 5, 20093:55:00 PM
 * @version 1.0
 */
public class PriviDeplyOpt extends DataOperator{

	/**
	 * 创建系统权限发布数据操作类
	 * @throws ErrorMessage
	 */
	public PriviDeplyOpt() throws ErrorMessage {
		super(PriviDeployStruc.Table_Name);
	}

	@Override
	protected OperatorResult _exchange() throws ErrorMessage {
		ArrayList<String> sql = new ArrayList<String>();
		if(opId.equals(PriviDeployOptCode.Query_All)){
			this.queryAll(sql, filter);
			return this.doing(sql, Operator_Type.Select);
		}else if(opId.equals(PriviDeployOptCode.Max_Seq)){
			this.getMaxSeq(sql, filter);
			return this.doing(sql, Operator_Type.Select);
		}else if(opId.equals(PriviDeployOptCode.Insert)){
			this.insert(sql, filter);
			return this.doing(sql, Operator_Type.DML);
		}else if(opId.equals(PriviDeployOptCode.Del)){
			this.delete(sql, filter);
			return this.doing(sql, Operator_Type.DML);
		}else if(opId.equals(PriviDeployOptCode.Edit)){
			this.update(sql, filter);
			return this.doing(sql, Operator_Type.DML);
		}else if(opId.equals(PriviDeployOptCode.Qurey_By_ID)){
			this.queryById(sql, filter);
			return this.doing(sql, Operator_Type.Select);
		}else{
			throw new ErrorMessage("Operator Exchange outport not found:"+ opId+" !");
		}
	}
	
	/**
	 *  查询所有系统权限大类
	 */
	private void queryAll(ArrayList<String> sql, DataFilter	filter){
		StringBuilder sp = new StringBuilder();
		sp.append(" select * from ");
		sp.append(this.tableName);
		sp.append(" order by ");
		sp.append(PriviDeployStruc.SEQ);
		sql.add(sp.toString());
	}

	/**
	 *  根据ID查询系统权限
	 */
	private void queryById(ArrayList<String> sql, DataFilter filter){
		StringBuilder sp = new StringBuilder();
		sp.append("select * from ");
		sp.append(this.tableName);
		sp.append(" where ");
		sp.append(PriviDeployStruc.DEPLOY_ID);
		sp.append("='");
		sp.append(filter.getValue());
		sp.append("'");
		sql.add(sp.toString());
	}
	
	/**
	 *  添加权限大类
	 * @throws ErrorMessage 
	 */
	private void insert(ArrayList<String> sql, DataFilter filter) throws ErrorMessage{
		
		Insert insert = new Insert(this.tableName);
		String deployID = this.generatorRowID();
		String typeName = filter.getValue(PriviDeployStruc.NAME);
		String typeDesc = filter.getValue(PriviDeployStruc.DESC);
		//ID
		insert.putStringFieldDenyNull(PriviDeployStruc.DEPLOY_ID, deployID);
		//名称
		insert.putStringFieldDenyNull(PriviDeployStruc.NAME, typeName);
		//描述
		insert.putStringFieldDenyNull(PriviDeployStruc.DESC, typeDesc);
		//入口操作ID
		insert.putStringFieldDenyNull(PriviDeployStruc.SHOW_ACT_ID, filter.getValue(PriviDeployStruc.SHOW_ACT_ID));
		
		//生成当前插入记录的序号(Sequence)
		OperatorResult rs = Operator.get(PriviDeployOptCode.Max_Seq, userId, new DataFilter());
		String maxSeq=rs.getValue(PriviDeployStruc.SEQ);
		if(maxSeq==null){
			maxSeq="1";
		}else{
			maxSeq=String.valueOf(Integer.parseInt(maxSeq)+1);
		}
		insert.putStringFieldDenyNull(PriviDeployStruc.SEQ, maxSeq);

		//生成当前插入记录的虚根ID
		String vID="-"+maxSeq;
		insert.putStringFieldDenyNull(PriviDeployStruc.VIRTUAL_ROOT_ID, vID);

		//生成当前插入记录的根ID
		String rootID="0"+maxSeq;
		insert.putStringFieldDenyNull(PriviDeployStruc.ROOT_ID, rootID);
		//添加权限大类
		sql.add(insert.getSimpleSql());
		
		//获得向权限表插入虚根的SQL
		IndexTableSimple menuType = IndexTableSimple.getNewInstance(userId, PriviStruc.Table_Name);
		sql.addAll(menuType.insertVirtualRoot(vID, null, typeName, typeDesc, true).getSqls());

		//获得向权限表插入根主题的SQL
		sql.addAll(menuType.insertFirst(Index_Tree_Node_Type.ROOT_THEME.toString(), 
				vID, rootID, typeName, null, typeDesc, null, true).getSqls());
	}
	
	/**
	 *  删除权限大类
	 * @throws ErrorMessage 
	 */
	private void delete(ArrayList<String> sql,DataFilter filter) throws ErrorMessage{
		//获取当前发布模型的根主题ID和虚根ID
		OperatorResult rs=Operator.get(PriviDeployOptCode.Qurey_By_ID, 
				userId, new DataFilter(filter.getValue()));
		if(!TOOLS.exist(rs)){
			throw new ErrorMessage("Cann't query this id:("+filter.getValue()+")");
		}
		//根主题ID(即在索引表中的根主题NodeID)
		String rootId=rs.getValue(PriviDeployStruc.ROOT_ID);
		//虚根ID
		String vRootId=rs.getValue(PriviDeployStruc.VIRTUAL_ROOT_ID);
		//到权限表中查询已发布的权限大类是否是叶子节点(即:是否有下级)
		IndexTable table = IndexTable.getNewInstance(userId, 
				PriviStruc.Table_Name, rootId);
		
		if(table.getIsLeaf()){////是叶子节点，没有下级，可以删除
			Delete dsql=new Delete(this.tableName);
			String id=filter.getValue();
			if(id==null){
				throw new ErrorMessage("Delete sql necessary have ID value! ");
			}
			dsql.setWhere(PriviDeployStruc.DEPLOY_ID+"='"+filter.getValue()+"'");
			sql.add(dsql.getSimpleSql());
			
			//权限表根主题删除
			sql.addAll(table.getDeleteSql(rootId).getSqls());
			//权限表虚根节点删除
			sql.addAll(table.getDeleteVirtualNodeSql(vRootId).getSqls());
		}
	}
	
	/**
	 *  更新权限大类
	 * @throws ErrorMessage 
	 */
	private void update(ArrayList<String> sql, DataFilter filter) throws ErrorMessage{
		//获取当前发布模型的根主题ID和虚根ID
		OperatorResult rs=Operator.get(PriviDeployOptCode.Qurey_By_ID, 
				userId, new DataFilter(filter.getValue()));
		if(!TOOLS.exist(rs)){
			throw new ErrorMessage("Cann't query this id:("+filter.getValue()+")");
		}
		//根主题ID(即在索引表中的根主题NodeID)
		String rootId=rs.getValue(PriviDeployStruc.ROOT_ID);
		//虚根ID
		String vRootId=rs.getValue(PriviDeployStruc.VIRTUAL_ROOT_ID);
		
		//更新权限发布表
		String name = filter.getValue(PriviDeployStruc.NAME);
		String desc = filter.getValue(PriviDeployStruc.DESC);
		Update update = new Update(this.tableName);
		update.setWhere(PriviDeployStruc.DEPLOY_ID+"='"+filter.getValue()+"'");
		update.putStringFieldIgnoreNull(PriviDeployStruc.NAME, 
				name);
		update.putStringFieldIgnoreNull(PriviDeployStruc.DESC, 
				desc);
		update.putStringFieldIgnoreNull(PriviDeployStruc.SHOW_ACT_ID, 
				filter.getValue(PriviDeployStruc.SHOW_ACT_ID));
		sql.add(update.getSimpleSql());
		
		//更新权限表根主题和虚根主题
		IndexTableSimple table = IndexTableSimple.getNewInstance(userId, PriviStruc.Table_Name);
		sql.addAll(table.update(rootId, name, desc, null, true).getSqls());
		sql.addAll(table.update(vRootId, name, desc, null, true).getSqls());
	}
	
	/**
	 * 查询当前表中的最大序号
	 */
	private void getMaxSeq(ArrayList<String> sql,DataFilter filter) throws ErrorMessage{
		StringBuilder sb = new StringBuilder("select max(seq) seq from ");
		sb.append(this.tableName);
		sql.add(sb.toString());
	}
}
